package ru.hh.team02.chat.database;

import ru.hh.team02.chat.messaging.PrivateMessage;
import ru.hh.team02.chat.server.Services;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Collections.*;

public class DatabaseServiceDerby implements DatabaseServiceInterface {
    private String dbURL = "jdbc:derby:hh0001team02;user=team02;create=false";
    private Connection conn = null;
    private Statement stmt = null;

    public DatabaseServiceDerby() {
        try {
            Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
            //Get a connection
            conn = DriverManager.getConnection(dbURL);
        } catch (Exception except) {
            except.printStackTrace();
        }
    }

    public void Close() {
        try  {
            if (stmt != null) {
                stmt.close();
            }
            if (conn != null) {
                DriverManager.getConnection("jdbc:derby:;shutdown=true");
                conn.close();
            }
        }
        catch (SQLException sqlExcept)  {
            if ( !sqlExcept.getSQLState().equals("XJ015") ) {
                sqlExcept.printStackTrace();
            }
        }
    }

    @Override
    public boolean clientExists(String name) {
        boolean result = false;
        try {
            stmt = conn.createStatement();
            ResultSet resultSet = stmt.executeQuery("select id from users where name = '" + name + "'");
            result = (resultSet.next());
            resultSet.close();
            stmt.close();
        } catch (SQLException sqlExcept) {
            sqlExcept.printStackTrace();
        }
        return result;
    }

    @Override
    public String getPasswordByClientName(String name) {
        String result = null;
        try {
            stmt = conn.createStatement();
            ResultSet resultSet = stmt.executeQuery("select password from users where name = '" + name + "'");
            if (resultSet.next()) {
                result = resultSet.getString("password");
            }
            resultSet.close();
            stmt.close();
        } catch (SQLException sqlExcept) {
            sqlExcept.printStackTrace();
        }
        return result;
    }

    @Override
    public String getRoomNameByClientName(String name) {
        String result = null;
        try {
            stmt = conn.createStatement();
            ResultSet resultSet = stmt.executeQuery("select rooms.name from users join rooms on users.room_id = rooms.id where users.name = '" + name + "'");
            if (resultSet.next()) {
                result = resultSet.getString("name");
            }
            resultSet.close();
            stmt.close();
        } catch (SQLException sqlExcept) {
            sqlExcept.printStackTrace();
        }
        return result;
    }

    @Override
    public int putNewPersonalMessageIntoDatabase(String message, String recepientName) {
        int result = 0;
        try {
            stmt = conn.createStatement();
            ResultSet resultSet = stmt.executeQuery("select id from users where name = '" + recepientName + "'");
            if (resultSet.next()) {
                int rctpto_id = resultSet.getInt("id");
                stmt.executeUpdate("insert into messages(message, rctpto_id) values ('" + message + "', " + rctpto_id + ")", Statement.RETURN_GENERATED_KEYS);
                ResultSet generatedKeys = stmt.getGeneratedKeys();
                if (generatedKeys.next()) {
                    result = generatedKeys.getInt(1);
                }
                generatedKeys.close();
            }
            resultSet.close();
            stmt.close();
        } catch (SQLException sqlExcept) {
            sqlExcept.printStackTrace();
        }

        Services.ADMIN_LOGGER.write(message + " in database");
        return result;
    }

    @Override
    public boolean markPersonalMessageAsDelivered(int id) {
        String message = getMessagesById(id).getText();

        try {
            stmt = conn.createStatement();
            stmt.execute("delete from messages where id = " + id);
            stmt.close();
        } catch (SQLException sqlExcept) {
            sqlExcept.printStackTrace();
            return false;
        }

        Services.ADMIN_LOGGER.write(message + " has been delivered and deleted from DB.");
        return true;
    }

    @Override
    public List<PrivateMessage> getAllUndeliveredMessagesToTheClient(String clientName) {
        List<PrivateMessage> result = new ArrayList<>();
        try {
            stmt = conn.createStatement();
            ResultSet resultSet = stmt.executeQuery("select messages.id, messages.message from messages " +
                                                    "join users on messages.rctpto_id = users.id " +
                                                    "where users.name = '" + clientName + "'");
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String message  = resultSet.getString("message");
                result.add(new PrivateMessage(message, id));
            }
            resultSet.close();
            stmt.close();
        } catch (SQLException sqlExcept) {
            sqlExcept.printStackTrace();
            return null;
        }

        for (PrivateMessage m : result) {
            String message = m.getText();
            Services.ADMIN_LOGGER.write(message + " is on the way");
        }

        return result;
    }

    @Override
    public PrivateMessage getMessagesById(int id) {
        PrivateMessage result = null;
        try {
            stmt = conn.createStatement();
            ResultSet resultSet = stmt.executeQuery("select messages.message, users.name from messages " +
                                                    "join users on messages.rctpto_id = users.id " +
                                                    "where messages.id = " + id);
            if (resultSet.next()) {
                String message  = resultSet.getString("message");
                String name  = resultSet.getString("name");
                result = new PrivateMessage(message, id);
            }
            resultSet.close();
            stmt.close();
        } catch (SQLException sqlExcept) {
            sqlExcept.printStackTrace();
        }
        return result;
    }

    @Override
    public String[] getAllRooms() {
        List<String> result = new ArrayList<String>();
        try {
            stmt = conn.createStatement();
            ResultSet resultSet = stmt.executeQuery("select name from rooms");
            while (resultSet.next()) {
                result.add(resultSet.getString("name"));
            }
            resultSet.close();
            stmt.close();
        } catch (SQLException sqlExcept) {
            sqlExcept.printStackTrace();
            return null;
        }


        return result.toArray(new String[result.size()]);
    }

    @Override
    public void changeRoom(String clientName, String room) {
        try {
            stmt = conn.createStatement();
            ResultSet resultSet = stmt.executeQuery("select id from rooms where rooms.name = '" + room + "'");
            if (resultSet.next()) {
                int room_id = resultSet.getInt("id");
                stmt.executeUpdate("update users set room_id = " + room_id + " where name = '" + clientName + "'");
            }
            resultSet.close();
            stmt.close();
        } catch (SQLException sqlExcept) {
            sqlExcept.printStackTrace();
        }
    }
}
